package com.ruoyi.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ruoyi.appuser.domain.Appuser;
import com.ruoyi.appuser.domain.AppuserPrizeRecord;
import com.ruoyi.appuser.domain.AppuserVipRecord;
import com.ruoyi.appuser.domain.vo.AppSeasonInfoVo;
import com.ruoyi.appuser.domain.vo.AppuserPrizeInfoVo;
import com.ruoyi.appuser.domain.vo.AppuserTaskVo;
import com.ruoyi.appuser.domain.vo.AppuserVO;
import com.ruoyi.appuser.service.IAppuserPrizeRecordService;
import com.ruoyi.appuser.service.IAppuserService;
import com.ruoyi.appuser.service.IAppuserVipRecordService;
import com.ruoyi.codebase.domain.CodeBase;
import com.ruoyi.codebase.service.ICodeBaseService;
import com.ruoyi.commodity.domain.Commodity;
import com.ruoyi.commodity.service.ICommodityService;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.constant.NumberConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.configure.domain.Configure;
import com.ruoyi.configure.service.IConfigureService;
import com.ruoyi.integral.domain.Integral;
import com.ruoyi.integral.service.IIntegralService;
import com.ruoyi.locker.domain.Locker;
import com.ruoyi.locker.service.ILockerService;
import com.ruoyi.normal.domain.AppuserAchievementPrize;
import com.ruoyi.normal.domain.NormalTask;
import com.ruoyi.normal.domain.NormalTaskRecord;
import com.ruoyi.normal.service.IAppuserAchievementPrizeService;
import com.ruoyi.normal.service.INormalTaskRecordService;
import com.ruoyi.normal.service.INormalTaskService;
import com.ruoyi.season.domain.PlaySeason;
import com.ruoyi.season.domain.PlaySeasonCommonTask;
import com.ruoyi.season.domain.PlaySeasonPrize;
import com.ruoyi.season.domain.PlaySeasonRecord;
import com.ruoyi.season.domain.PlaySeasonTaskRecord;
import com.ruoyi.season.service.IPlaySeasonCommonTaskService;
import com.ruoyi.season.service.IPlaySeasonPrizeService;
import com.ruoyi.season.service.IPlaySeasonRecordService;
import com.ruoyi.season.service.IPlaySeasonService;
import com.ruoyi.season.service.IPlaySeasonTaskRecordService;
import com.ruoyi.util.AuthUtil;
import com.ruoyi.util.DateUtils;
import com.ruoyi.video.domain.PlaySeasonTaskVideo;
import com.ruoyi.video.service.IPlaySeasonTaskVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * @author mjl
 */
@RestController
@RequestMapping("/app-api/index")
@Api(value = "首页", tags = "移动端接口")
public class AppIndexController {
    private static final Logger logger = LoggerFactory
         						   .getLogger(AppIndexController.class);

    @Resource
    private ICommodityService commodityService;
    @Resource
    private IAppuserService appuserService;
    @Resource
    private ICodeBaseService codeBaseService;
    @Resource
    private IAppuserVipRecordService appuserVipRecordService;
    @Resource
    private IAppuserAchievementPrizeService appuserAchievementPrizeService;

    @Resource
    private IPlaySeasonService playSeasonService;
    @Resource
    private IPlaySeasonPrizeService playSeasonPrizeService;
    @Resource
    private IPlaySeasonRecordService playSeasonRecordService;
    @Resource
    private IConfigureService configureService;
    @Resource
    private IPlaySeasonCommonTaskService playSeasonCommonTaskService;
    @Resource
    private INormalTaskService normalTaskService;
    @Resource
    private IIntegralService integralService;

    @Resource
    private IPlaySeasonTaskVideoService playSeasonTaskVideoService;
    @Resource
    private INormalTaskRecordService normalTaskRecordService;
    @Resource
    private IPlaySeasonTaskRecordService playSeasonTaskRecordService;
    @Resource
    private ILockerService lockerService;
    @Resource
    private IAppuserPrizeRecordService appuserPrizeRecordService;



    @GetMapping("/indexInfo")
    @ApiOperation(value = "首页展示")
    public R getUserInfo() {
        String loginUserId = AuthUtil.getAppUserId();
        HashMap<String,Object> result = new HashMap(5);
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);

        AppuserPrizeInfoVo prizeInfo = new AppuserPrizeInfoVo();
        AppSeasonInfoVo seasonInfo = new AppSeasonInfoVo();

        if(Objects.nonNull(appuser))
        {
            /**赛季记录信息*/
            PlaySeasonRecord playRecord = playSeasonRecordService.getById(appuser.getPlaySeasonRecordId());

            /**赛季信息*/
            PlaySeason playSeason = playSeasonService.getById(playRecord.getPlaySeasonId());
            if(playSeason.getType() != 1){
                Commodity commodity = commodityService.getOne(new LambdaQueryWrapper<Commodity>()
                        .eq(Commodity :: getPlaySeasonId,playSeason.getId())
                );

                seasonInfo.setCid(commodity.getId());
            }

            seasonInfo.setName(playSeason.getName());
            seasonInfo.setPicture(playSeason.getPicture());
            seasonInfo.setPlaySeasonId(playSeason.getId());

            List<PlaySeasonPrize> prizeList = new ArrayList<>();
            if(NumberConstants.TWO_NUMBER.equals(appuser.getIsVip()))
            {/**会员*/
                appuser.setShowIntegral(appuser.getVipIntegral());
                /**奖品信息*/
                prizeList = playSeasonPrizeService
                        .selectPlayCurrentPrize(playRecord.getId(),playRecord.getPlaySeasonId());
            }else if(NumberConstants.ONT_NUMBER.equals(appuser.getIsVip()))
            {/**普通用户*/
                appuser.setShowIntegral(appuser.getNormalIntegral());
                prizeList = playSeasonPrizeService
                        .selectNormalUserCurrentPrize(playRecord.getPlaySeasonId());
            }

            if(prizeList.size() > 0){
                PlaySeasonPrize seasonPrize = prizeList.get(0);
                prizeInfo.setPlayIntegral(seasonPrize.getIntegral());
                prizeInfo.setPicture(seasonPrize.getPicture());
                prizeInfo.setPrizeName(seasonPrize.getPrizeName());
                prizeInfo.setId(seasonPrize.getId());
            }


            /**任务*/
            List<AppuserTaskVo> taskInfo = playSeasonCommonTaskService
                    .selectPlaySeasonTask(playSeason.getId());

            if (taskInfo.size() > 0) {
                for (AppuserTaskVo temp : taskInfo) {
                    Integer completedCounts =  playSeasonTaskRecordService.selectRecordCounts(loginUserId
                            ,appuser.getPlaySeasonRecordId(),temp.getTaskId());
                    temp.setCompletedCounts(completedCounts);
                }

            }
            prizeInfo.setAppuserTask(taskInfo);

           /**积分差*/
           if(Objects.nonNull(prizeInfo) && StringUtils.isNotBlank(prizeInfo.getId())){
               if(appuser.getShowIntegral().compareTo(prizeInfo.getPlayIntegral()) >= 0){
                   prizeInfo.setDifferIntegral(new BigDecimal(0));
               }else{
                   prizeInfo.setDifferIntegral(prizeInfo.getPlayIntegral().subtract(appuser.getShowIntegral()));
               }
           }


        }

        result.put("seasonInfo",seasonInfo);
        result.put("prizeInfo",prizeInfo);
        result.put("appuser",appuser);
        return R.ok(result);
    }



//    @PostMapping("/vip")
//    @ApiOperation(value = "vip兑换",notes = "code 会员码")
//    @Transactional
    public R vip(String code) {
        if(StringUtils.isBlank(code) || code.length() != NumberConstants.SIX_NUMBER){
            return R.fail("兑换码错误");
        }
        String loginUserId = AuthUtil.getAppUserId();
        Appuser appuser = appuserService.getById(loginUserId);
        if(appuser.getIsVip() == 2){
            return R.fail("您已经是会员,请勿重复兑换");
        }

        List<CodeBase> codeInfo = codeBaseService.list(new LambdaQueryWrapper<CodeBase>()
                .eq(CodeBase :: getCode,code));
        if(CollectionUtils.isEmpty(codeInfo)){
            return R.fail("会员码不存在");
        }
        if(codeInfo.size() > 1){
            return R.fail("会员码异常,请联系客服");
        }
        AppuserVipRecord vipRecord = appuserVipRecordService.getOne(new LambdaQueryWrapper<AppuserVipRecord>()
                        .eq(AppuserVipRecord :: getCodeBaseId,codeInfo.get(0).getId())
                        .eq(AppuserVipRecord :: getAppuserId,loginUserId));
        if(Objects.nonNull(vipRecord)) {
            return R.fail("您已兑换过,请勿重复兑换");
        }
        AppuserVipRecord record = appuserVipRecordService.getOne(new LambdaQueryWrapper<AppuserVipRecord>()
                .eq(AppuserVipRecord :: getCodeBaseId,codeInfo.get(0).getId())
                .ne(AppuserVipRecord :: getAppuserId,loginUserId));
        if(Objects.nonNull(record)) {
            return R.fail("该兑换码已被别人兑换");
        }

        Date date = new Date();
        /**查询当前赛季*/
        PlaySeason playSeason = playSeasonService.getOne(new LambdaUpdateWrapper<PlaySeason>()
            .eq(PlaySeason :: getIsCurrent,2));

        if(Objects.isNull(playSeason)){
            return R.fail("兑换失败,请稍后重试");
        }
        /**参加赛季记录*/
        PlaySeasonRecord playSeasonRecord = new PlaySeasonRecord();
        playSeasonRecord.setAppuserId(loginUserId);
        playSeasonRecord.setBeginTime(date);
        playSeasonRecord.setEndTime(DateUtils.getTime(date, 30));
        playSeasonRecord.setCreateTime(date);
        playSeasonRecord.setPlaySeasonId(playSeason.getId());
        if(!playSeasonRecordService.save(playSeasonRecord)){
            return R.fail("赛季记录失败");
        }


        if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                .set(Appuser :: getIsVip,NumberConstants.TWO_NUMBER)
                .set(Appuser :: getVipTime,date)
                .set(Appuser :: getUpdateTime,date)
                .set(Appuser :: getPlaySeasonRecordId,playSeasonRecord.getId())
                .eq(Appuser :: getId,loginUserId))){
            return R.fail("开通会员失败,请重新尝试");
        }

        AppuserVipRecord appuserVipRecord = new AppuserVipRecord();
        appuserVipRecord.setAppuserId(loginUserId);
        appuserVipRecord.setCreateTime(date);
        appuserVipRecord.setCodeBaseId(codeInfo.get(0).getId());
        if(!appuserVipRecordService.save(appuserVipRecord)){
            return R.fail("会员记录失败");
        }


        return R.ok();
    }


    @GetMapping("/integralDetail")
    @ApiOperation(value = "积分明细",notes = " pageNo起始页,pageSize页数")
    public R integralDetail(@RequestParam(name = "pageNo" ,defaultValue = "1") Integer pageNo
            ,@RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize) {
        String loginUserId = AuthUtil.getAppUserId();
        IPage<Integral> page = new Page<Integral>(pageNo,pageSize);
        IPage<Integral> list = integralService.page(page,
                new LambdaQueryWrapper<Integral>().eq(Integral::getAppuserId,loginUserId)
                        .orderByDesc(Integral::getCreateTime));
        return R.ok(list);
    }


    @GetMapping("/getVideo")
    @ApiOperation(value = "观看视频任务",notes = "")
    public R getVideo() {
        String loginUserId = AuthUtil.getAppUserId();
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);
        PlaySeasonRecord playRecord = playSeasonRecordService.getById(appuser.getPlaySeasonRecordId());

        Integer  size = playSeasonTaskVideoService.selectVideoCount(playRecord.getPlaySeasonId());

        Random random = new Random();
        int randomNum = random.nextInt(size);

        PlaySeasonTaskVideo videoInfo = playSeasonTaskVideoService.selectVideoInfo(randomNum,playRecord.getPlaySeasonId());
        HashMap<String,Object> map = new HashMap(4);

        Configure configInfo = configureService.list().get(0);
        map.put("playTime",configInfo.getPlayTime());
        map.put("videoInfo",videoInfo);
        return R.ok(map);
    }


    @PostMapping("/videoTask")
    @ApiOperation(value = "观看视频任务完成",notes = "taskId任务id")
    public R videoTask(String taskId) {
        if(StringUtils.isBlank(taskId)){
           return R.fail("任务信息错误");
        }
        String loginUserId = AuthUtil.getAppUserId();
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);
        /**已完成任务次数*/
        Integer completedCounts =  playSeasonTaskRecordService.selectRecordCounts(loginUserId
                ,appuser.getPlaySeasonRecordId(),taskId);

        Date date = new Date();
        PlaySeasonCommonTask taskInfo = playSeasonCommonTaskService.getById(taskId);
        if(completedCounts.compareTo(taskInfo.getCounts()) >= 0){
            return R.fail("今日任务已达上限");
        }
        BigDecimal proft = taskInfo.getVipIntegral();
        BigDecimal afterIntegral =  new BigDecimal(0);


        if(appuser.getIsVip() == 1){
            /**普通*/
             afterIntegral = proft.add(appuser.getNormalIntegral());
            if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                    .set(Appuser :: getNormalIntegral,afterIntegral)
                    .set(Appuser::getUpdateTime,date)
                    .eq(Appuser::getId,loginUserId))){
                return R.fail("用户积分更新失败");

            }
        }else if(appuser.getIsVip() == 2){
            /**会员*/
             afterIntegral = proft.add(appuser.getVipIntegral());
            if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                    .set(Appuser :: getVipIntegral,afterIntegral)
                    .set(Appuser::getUpdateTime,date)
                    .eq(Appuser::getId,loginUserId))){
                return R.fail("用户积分更新失败");

            }
        }
        /**更新任务记录*/
        PlaySeasonTaskRecord record = new PlaySeasonTaskRecord();
        record.setCreateTime(date);
        record.setPlaySeasonRecordId(appuser.getPlaySeasonRecordId());
        record.setTaskId(taskId);
        if(!playSeasonTaskRecordService.save(record)){
            return R.fail("任务记录更新失败");
        }

        Integral insertIntegral = new Integral();

        insertIntegral.setContent(taskInfo.getName());
        insertIntegral.setAppuserId(loginUserId);
        insertIntegral.setBalance(afterIntegral);
        insertIntegral.setProfit(proft);
        insertIntegral.setType(2);
        insertIntegral.setCreateTime(date);
        if(!integralService.save(insertIntegral)){
            return R.fail("积分记录失败");
        }

        return R.ok();
    }

//    @PostMapping("/getPrize")
//    @ApiOperation(value = "领取奖品",notes = "")
    public R getPrize() {
        String loginUserId = AuthUtil.getAppUserId();
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);
        Date date = new Date();

        BigDecimal afterIntegral = new BigDecimal(0);
        if(appuser.getIsVip() == 1){
            /**普通*/
            /**奖品信息*/
            AppuserAchievementPrize achievementPrize = appuserAchievementPrizeService.getOne(
                    new LambdaQueryWrapper<AppuserAchievementPrize>());

            BigDecimal userIntegral = appuser.getNormalIntegral();
            while(userIntegral.compareTo(achievementPrize.getIntegral()) >= 0){

                afterIntegral = userIntegral.subtract(achievementPrize.getIntegral());
                if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                        .set(Appuser::getNormalIntegral,afterIntegral)
                        .set(Appuser::getUpdateTime,date)
                        .eq(Appuser::getId,loginUserId)
                )){
                    return R.fail("更新用户积分失败");
                }
                isGetInfo(achievementPrize.getPicture(),achievementPrize.getId(),date,loginUserId,
                        achievementPrize.getPrizeName(),
                        achievementPrize.getIntegral(),
                        afterIntegral,null);
                userIntegral = userIntegral.subtract(achievementPrize.getIntegral());
            }

        }else if(appuser.getIsVip() == 2){
            /**会员*/
            PlaySeasonRecord playRecord = playSeasonRecordService.getById(appuser.getPlaySeasonRecordId());
            /**奖品信息根据积分正序*/
            List<PlaySeasonPrize> prizeList = playSeasonPrizeService
                    .selectPlayCurrentPrize(playRecord.getId(),playRecord.getPlaySeasonId());

            if(prizeList.size() > 0){
                BigDecimal userIntegral = appuser.getVipIntegral();

                 for(PlaySeasonPrize temp : prizeList)
                 {
                     if(userIntegral.compareTo(temp.getIntegral()) >= 0)
                     {

                         afterIntegral = userIntegral.subtract(temp.getIntegral());
                         if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                                 .set(Appuser::getVipIntegral,afterIntegral)
                                 .set(Appuser::getUpdateTime,date)
                                 .eq(Appuser::getId,loginUserId)
                         )){
                             return R.fail("更新用户积分失败");
                         }
                         isGetInfo(temp.getPicture(),temp.getId(),date,loginUserId,
                                 temp.getPrizeName(),
                                 temp.getIntegral(),
                                 afterIntegral,appuser.getPlaySeasonRecordId());
                         userIntegral = userIntegral.subtract(temp.getIntegral());

                     }
                  }

            }

        }

        return R.ok();
    }

    public void isGetInfo(String picture,String prizeId,Date date ,String loginUserId,String name,BigDecimal proft,
                          BigDecimal afterIntegral,String playSeasonRecordId){
        Integral insertIntegral = new Integral();
        insertIntegral.setContent(name);
        insertIntegral.setAppuserId(loginUserId);
        insertIntegral.setBalance(afterIntegral);
        insertIntegral.setProfit(proft);
        insertIntegral.setType(1);
        insertIntegral.setCreateTime(date);
        if(!integralService.save(insertIntegral)){
            logger.error("领取奖励，积分记录失败");
        }

        AppuserPrizeRecord prizeRecord = new AppuserPrizeRecord();
        prizeRecord.setAppuserId(loginUserId);
        prizeRecord.setCreateTime(date);
        prizeRecord.setPrizeName(name);
        prizeRecord.setPicture(picture);
        prizeRecord.setPlaySeasonPrizeId(prizeId);
        prizeRecord.setPlaySeasonRecordId(playSeasonRecordId);
        if(!appuserPrizeRecordService.save(prizeRecord)){
            logger.error("领取奖励，更新领奖记录失败");
        }

        Locker locker = new Locker();
        locker.setName(name);
        locker.setPicture(picture);
        locker.setType(2);
        locker.setAppuserId(loginUserId);
        locker.setCreateTime(date);
        if(!lockerService.save(locker)){
            logger.error("领取奖励失败");
        }
    }


//    @PostMapping("/userInfo")
//    @ApiOperation(value = "获取用户信息",notes = "")
    public R userInfo() {
        String loginUserId = AuthUtil.getAppUserId();
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);
        if(Objects.nonNull(appuser)){
            if(NumberConstants.TWO_NUMBER.equals(appuser.getIsVip()))
            {/**会员*/

                appuser.setShowIntegral(appuser.getVipIntegral());
            }else if(NumberConstants.ONT_NUMBER.equals(appuser.getIsVip())){
                appuser.setShowIntegral(appuser.getNormalIntegral());
            }
        }
        return R.ok(appuser);
    }

    @PostMapping("/signIn")
    @ApiOperation(value = "签到",notes = "")
    public R signIn() {
        String loginUserId = AuthUtil.getAppUserId();
        if(StringUtils.isBlank(loginUserId)){
           return R.fail("用户不存在");
        }
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);

        if(Objects.nonNull(appuser) || StringUtils.isNotBlank(appuser.getId())){
            Configure configInfo = configureService.list().get(0);
            BigDecimal proft = new BigDecimal(0);
             if(appuser.getIsVip() == 1){
                  appuser.setShowIntegral(appuser.getNormalIntegral());
                  proft = configInfo.getNormalSign();
             }else if(appuser.getIsVip() == 2){
                 appuser.setShowIntegral(appuser.getVipIntegral());

                 proft = configInfo.getVipSign();
             }

            Integral appuserSignInfo = integralService.selectIntegral(loginUserId);
            if(Objects.nonNull(appuserSignInfo)){
               return R.fail("请勿重复签到");
            }
            Integral insertIntegral = new Integral();
            insertIntegral.setContent("签到");
            insertIntegral.setAppuserId(loginUserId);
            insertIntegral.setBalance(proft.add(appuser.getShowIntegral()));
            insertIntegral.setProfit(proft);
            insertIntegral.setType(2);
            insertIntegral.setCreateTime(new Date());
            insertIntegral.setClassify(1);
            if(!integralService.save(insertIntegral)){
                logger.error("积分记录失败");
            }

        }

        return R.ok();
    }



}
